package com.github.ginirohikocha.dbm.util;

import android.support.annotation.NonNull;
import android.util.Log;

import com.github.ginirohikocha.dbm.Address;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {

    public static void sendOkHttpPostRequest(String address, RequestBody requestBody, okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }

    public static void sendOkHttpPatchRequest(String address, RequestBody requestBody, okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .patch(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }

    public static void updateLocation(String workerNum, double latitude, double longitude) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("workerNum", workerNum);
        jsonObject.put("latitude", latitude);
        jsonObject.put("longitude", longitude);

        final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());

        HttpUtil.sendOkHttpPostRequest(Address.WORKER_UPDATE_LOCATION, requestBody, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                Log.d("定位更新", responseBody);
            }
        });
    }
}
